package com.ljy.my_study.spring.tiny.study8.beans.factory;

import java.lang.reflect.Field;
import java.util.List;

import com.ljy.my_study.spring.tiny.study7.beans.BeanDefinition;
import com.ljy.my_study.spring.tiny.study7.beans.BeanReference;
import com.ljy.my_study.spring.tiny.study7.beans.PropertyValue;

public class AutowireCapableBeanFactory extends AbstractBeanFactory{

	
	
	@Override
	public Object doCreateBean(BeanDefinition beanDefinition) throws Exception {
		Object bean=createBeanInstance(beanDefinition);
		beanDefinition.setBean(bean);
		applyPropertyValues(beanDefinition);
		return bean;
	}
	
	public Object createBeanInstance(BeanDefinition beanDefinition) throws Exception {
		Object bean=beanDefinition.getBeanClass().newInstance();
		return bean;
	}

	public void applyPropertyValues(BeanDefinition beanDefinition) throws Exception {
		Object bean=beanDefinition.getBean();
		List<PropertyValue> propertyValues=beanDefinition.getPropertyValues().getPropertyValues();
		for(PropertyValue p:propertyValues) {
			Field field=bean.getClass().getDeclaredField(p.getName());
			field.setAccessible(true);
			Object value =p.getValue();
			if(value instanceof BeanReference) {
				BeanReference beanReference=(BeanReference) value;
				value=getBean(beanReference.getName());
			}
			field.set(bean, value);
		}
	}
}
